#include "StdAfx.h"
#include "GStringUtil.h"

#include <cctype>


GStringUtil::GStringUtil(void)
{
}


GStringUtil::~GStringUtil(void)
{
}

wchar_t * GStringUtil::cstr2wstr( const char * src ){
	size_t len = strlen( src ) + 1;
	size_t converted;
	wchar_t * dst = new wchar_t[ len ];
	mbstowcs_s( &converted, dst, len, src, _TRUNCATE);
	return dst;
}

char * GStringUtil::wstr2cstr( const wchar_t * src ){
	size_t len = wcslen( src ) + 1;
	size_t converted;
	char * dst = new char[ len ];
	wcstombs_s( &converted, dst, len, src, _TRUNCATE);
	return dst;
}

char * GStringUtil::substr( char * dst, const char * src, int startIndex, int endIndex ){
	for ( int i = startIndex, j = 0; i < endIndex; ++i, ++j )
		dst[ j ] = src[ i ];
	dst[ endIndex - startIndex ] = '\0';
	return dst;
}

bool GStringUtil::analyseFilePath( const char * fullPath, char * filePath, char * fileName, char * ext ){
	if( !fullPath )
		return false;
	size_t fullLen = strlen( fullPath );
	int startIndex = 0;
	int dotIndex = fullLen;
	bool dotMet = false;
	for( int i = fullLen - 1; i >= 0; --i )
		if( fullPath[ i ] == '.' ){
			if ( !dotMet ){
				dotIndex = i;
				dotMet = true;
			}
		} else if( fullPath[ i ] == '\\' ){
			startIndex = i + 1;
			break;
		}
	if( filePath ){
		strncpy( filePath, fullPath, startIndex );
		filePath [ startIndex ] = '\0';
	}
	if( fileName )
		substr( fileName, fullPath, startIndex, dotIndex );
	if( ext )
		substr( ext, fullPath, dotIndex + 1, fullLen );
	return true;
}

char ** GStringUtil::split( const char * src, const char sep, int& segNum ){
	if( !src || strcmp( src, "" ) == 0 ){
		segNum = 0;
		return 0;
	}
	int segCount = 1;
	size_t srcLen = strlen( src );
	for( size_t i = 0; i < srcLen; ++i )
		if( src[ i ] == sep )
			++segCount;
	int* segLens = new int[ segCount ];
	int len = 0;
	int segIndex = 0;
	for( size_t i = 0; i < srcLen; ++i ){
		if( src[ i ] != sep )
			++len;
		else{
			segLens[ segIndex++ ] = len;
			len = 0;
		}
	}
	segLens[ segIndex ] = len;
	char** splitStr = new char*[ segCount ];
	int startIndex = 0;
	for( int i = 0; i < segCount; ++i ){
		splitStr[ i ] = new char[ segLens[ i ] + 1 ];
		substr( splitStr[ i ], src, startIndex, startIndex + segLens[ i ] );
		startIndex += segLens[ i ] + 1;
	}
	delete [] segLens;
	segNum = segCount;
	return splitStr;
}

void GStringUtil::toLowerCase( char* str ){
	size_t len = strlen( str );
	for( size_t i = 0; i< len; ++i )
		str[ i ] = tolower( str[ i ] );
}

void GStringUtil::toUpperCase( char* str ){
	size_t len = strlen( str );
	for( size_t i = 0; i < len; ++i )
		str[ i ] = toupper( str[ i ] );
}
